/**
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import xml from '@ohos.convertxml';
import {SVGXMLChecker} from "./SVGXMLChecker"

/**
 * SVG管理器
 */
export class SVGManager {
  private static _sInstance: SVGManager;
  private _checker: SVGXMLChecker;

  public static getInstance(): SVGManager{
    if (!this._sInstance) {
      this._sInstance = new SVGManager();
    }
    return this._sInstance;
  }

  /**
   * 构造函数
   */
  private constructor() {
    this._checker = new SVGXMLChecker();
  }

  /**
   * 解析SVG字符串
   * @param fileString svg字符串
   * @param onSuccess 解析成功回调
   * @param onFailed 解析失败回调
   */
  public parseString(fileString: string, onSuccess: Function, onFailed?: Function): void{
    let that = this;
    var xmlInstance = new xml.ConvertXML();
    var xmlResult = xmlInstance.convert(fileString, {
      trim: false,
      declarationKey: 'declaration',
      instructionKey: 'instruction',
      attributesKey: 'attributes',
      textKey: 'text',
      cdataKey: 'cdata',
      doctypeKey: 'doctype',
      commentKey: 'comment',
      parentKey: 'parent',
      typeKey: 'type',
      nameKey: 'name',
      elementsKey: 'elements'
    });
    console.log("xmlResult:"+JSON.stringify(xmlResult));
    if (xmlResult) {
      onSuccess(JSON.stringify(xmlResult));
    } else {
      onFailed('SVGManager parse failed, result is empty');
    }
  }

}